package com.junjie.blibli.aspect;

import com.junjie.blibli.Entity.auth.UserRole;
import com.junjie.blibli.Exception.http.ConditionException;
import com.junjie.blibli.Support.UserSupport;
import com.junjie.blibli.annotation.ApiLimitedRole;
import com.junjie.blibli.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

//优先级
@Order(1)
@Aspect
@Component
public class ApiLimitedRoleAspect {
    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserRoleService userRoleService;

    //切点
    @Pointcut("@annotation(com.junjie.blibli.annotation.ApiLimitedRole)")
    public void check(){};

    @Before("check() && @annotation(apiLimitedRole)")
    public void doBefore(JoinPoint joinPoint, ApiLimitedRole apiLimitedRole){
        Long userId = userSupport.getCurrentUserId();
        //获取该用户的角色
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        //获取注解中的值
        String[] limitedRoleCodeList = apiLimitedRole.limitedRoleCodeList();
        //比对两个列表就行了，然后这里建议使用Set，因为Set不会存相同的元素
        //因为是数组，所以要先用Arrays.stream方法转换成stream流，再转set放进去
        Set<String> limitedRoleCodeSet = Arrays.stream(limitedRoleCodeList).collect(Collectors.toSet());
        //获取出角色编码
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        //然后取交集就可以了，剩下的就是交集
        roleCodeSet.retainAll(limitedRoleCodeSet);
        //哪怕有一个角色重合了，都不能调用这个接口
        if(roleCodeSet.size()>0) throw new ConditionException("权限不足！充钱少了");
    }

}
